package cn.yhp.mybatis.binding;

import cn.yhp.mybatis.mapping.MappedStatement;
import cn.yhp.mybatis.mapping.SqlCommandType;
import cn.yhp.mybatis.session.Configuration;
import cn.yhp.mybatis.session.SqlSession;

import java.lang.reflect.Method;

/**
 * 映射器方法
 * @author yhp
 * @date 2023/11/18
 */
public class MapperMethod {


    private final SqlCommand command;

    public MapperMethod(Class<?> mapperInterface,Method method,Configuration configuration){
        this.command=new SqlCommand(configuration,mapperInterface,method);
    }

    public Object execute(SqlSession sqlSession,Object[] args){
        Object result=null;
        switch (command.getType()){
            case INSERT:
                break;
            case DELETE:
                break;
            case UPDATE:
                break;
            case SELECT:
                result=sqlSession.selectOne(command.getName(),args);
                break;
            default:
                throw new RuntimeException("未知的执行方法："+command.getName());
        }
        return result;
    }

    /**
     * SQL指令
     */
    public static class SqlCommand{

        /**
         * mapper方法全包路径名
         */
        private final String name;

        /**
         * sql类型
         */
        private final SqlCommandType type;

        public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method){
            // 组成mapper接口全包名路径+方法名
            String statementName = mapperInterface.getName() + "." + method.getName();
            MappedStatement mappedStatement = configuration.getMappedStatement(statementName);
            name=mappedStatement.getId();
            type=mappedStatement.getSqlCommandType();
        }

        public String getName() {
            return name;
        }

        public SqlCommandType getType() {
            return type;
        }
    }
}
